define(['jquery',"bbcare","bld/app/patient/treatPlanCourseEdit.servers","bld/app/patient/treatPlanCourseEdit.ui"],function($,$bb,$servers,$ui){
    var treatPlanCourseEdit = {};
    var domId = "treatPlanCourseEditTable";
    var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
    var channelId = $bb.getChannelId();

    /**
     * 模态框小类回调函数2
     */
    var ajaxSmallClassCallBack02 = function(data,datas){
        datas.smallClass = data.medCatalogInfos;
        datas.status = "update";
        modalUi(datas,datas.medicines[datas.index]);
    }

    /**
     * 选择搜索出的某一个药品
     */
    var selectMedicineName = function() {
        var datas = $(this).data("datas");
        $("#inputQuery").hide();
        datas.index = $(this).index();
        var params = {
            "medCatalogInfo":{
                "classId":datas.medicines[datas.index].class_id
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClassCallBack02,datas);
    }

    /**
     * 选择药品名称回调函数
     */
    var ajaxSelectCallBack = function(data,datas) {
        if( data.rows.length > 0 ){
            datas.medicines = data.rows;
            $ui.selectCallBack({
                "id": "inputQuery",
                "list": data.rows
            });
            $("#inputQuery").show();
            $("#inputQuery .query_item").unbind("click");
            $("#inputQuery .query_item").data("datas",datas);
            $("#inputQuery .query_item").click(selectMedicineName);
        }else{
            $("#inputQuery").hide();
        }
    }

    /**
     * 查询药品名称回调函数
     */
    var onSelectByName = function() {
        var datas = $(this).data("datas");
        var medicineName = $("#medicineName").val();
        var params = {
            "medicineName": medicineName,
            "medicineType":"1"
        };
        $servers.ajaxSelect(params,ajaxSelectCallBack,datas);
    }
    
    /**
     * 模态框小类回调函数
     */
    var ajaxSmallClass = function(data) {
        $ui.smallClass({
            "dom": $("#catalogId"),
            "list": data.medCatalogInfos
        })
    }

    /**
     * 大类改变时触发
     */
    var onChangeBigClass = function(){
        var classId = $(this).val();
        var params = {
            "medCatalogInfo":{
                "classId":classId
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClass);
    }

    /**
     * 添加药品回调函数
    */
    var ajaxAddCallBack = function(data,datas) {
        $('.' + datas.className).modal('hide');
        tableInit();
    }

    /**
     * 添加药品
     */
    var onAdd = function() {
        var datas = $(this).data("datas");
        var id = $(this).attr("data-id");
        var medicineId = $(this).attr("data-medicineId");
        var medicineName = $.trim($("#medicineName").val());
        var classId = $("#classId").val();
        var catalogId = $("#catalogId").val();
        var frequencyDay = $("#frequencyDay").val();
        var frequencyTime = $("#frequencyTime").val();
        var calcuMethod = $("#calcuMethod").val();
        var medicineDose = $.trim($("#medicineDose").val());
        var medUnitId = $("#medUnitId").val();
        var medicineType = $("#medicineType").val();
        var character = $("#character").val();
        var indication = $("#indication").val();
        var adverseReaction = $("#adverseReaction").val();
        var taboo = $("#taboo").val();
        var considerations = $("#considerations").val();
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        if ( !medicineName || medicineName == '' ) {
            $bb.toastShow('药品名称不能为空');
            return;
        }
        if ( !frequencyDay || frequencyDay == '' ) {
            $bb.toastShow('服用周期天数不能为空');
            return;
        }
        if ( !frequencyTime || frequencyTime == '' ) {
            $bb.toastShow('服用周期次数不能为空');
            return;
        }
        if ( !medicineDose || medicineDose == '' ) {
            $bb.toastShow('药品剂量不能为空');
            return;
        }
        var params = {
            "oprInfo":{
                "opCode": "1251",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生向疗程中添加药品【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "medicineInfo":{
                "medicineName": medicineName,
                "classId": classId,
                "catalogId": catalogId,
                "id":medicineId
            },
            "medSkuInfo":{
                "medicineDose": medicineDose,
                "calcuMethod": calcuMethod,
                "frequencyDay": frequencyDay,
                "frequencyTime": frequencyTime,
                "useUnitId": medUnitId,
                "medicineType": medicineType,
                "medUnitId": medUnitId,
                "character": character,
                "indication": indication,
                "adverseReaction": adverseReaction,
                "taboo": taboo,
                "considerations": considerations,
                "id":id,
            },
            "ptCourseId":$bb.getPageParams().ptCourseId,
            "seqNo":$('#'+ domId +' thead tr th').length - 2,
        };
        $servers.ajaxAdd(params,ajaxAddCallBack,datas);
    }

    /**
     * 重置
     */
    var onReset = function(){
        var datas = $(this).data("datas");
        var obj = {};
        obj.status = "add";
        modalUi(datas,obj);
    }

    /**
     * 模态框初始化
     */
    var modalUi = function(datas,obj){
        var options = {
            "dom": $("." + datas.className + " .modal-body"),
            "status":datas.status,
            "units":datas.units,
            "bigClass":datas.bigClass,
            "smallClass":datas.smallClass,
        };
        if(obj) $.extend(options,obj);
        $ui.add(options);
        $("." + datas.className).modal("show");
        // 大类改变时触发
        $("#classId").unbind("change");
        $("#classId").change(onChangeBigClass);
        // 模态框内的药名搜索
        $("#medicineName").unbind("input propertychange");
        $("#medicineName").data("datas",datas);
        $("#medicineName").bind("input propertychange", onSelectByName);
        // 添加药品并应用给疗程
        $("#add").unbind("click");
        $("#add").data("datas",datas);
        $("#add").bind("click",onAdd);
        // 重置
        $("#reset").unbind("click");
        $("#reset").data("datas",datas);
        $("#reset").bind("click", onReset);
    }

    /**
     * 请求大类成功后的回调函数
     */
    var ajaxSmallClassCallBack = function(data,datas){
        datas.smallClass = data.medCatalogInfos;
        datas.className = "courseEditModal";
        $bb.modal({
            "className": datas.className,
            "tit": "药品添加页",
        }, function() {
            modalUi(datas);
        });
    }

    /**
     * 模态框大类回调函数
     */
    var ajaxBigClass = function(data,datas) {
        datas.bigClass = data.data;
        datas.status = "add";
        var params = {
            "medCatalogInfo":{
                "classId":data.data[0].id
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClassCallBack,datas);
    }

    /**
     * 查询药品单位回调函数
     */
    var ajaxQueryUnit = function(data,datas) {
        datas.units = data.medUnits;
        $servers.ajaxMedicineBigClass(ajaxBigClass,datas);
    }

    /**
     * 点击添加事件
     */
    var onAddClick = function() {
        var datas = {};
        $servers.ajaxQueryUnit(ajaxQueryUnit,datas);
    }

    /**
     * 请求删除疗程中的药品
     */
    var confirmDeleteMed = function(params) {
        $servers.ajaxRemoveCourseMedicine(params,tableInit);
    }

    /**
     * 删除药品
     */
    var deleteMed = function() {
        var medicineId = $(this).parent("th").attr('data-medicineId');
        var seqNo = parseInt($(this).parent("th").attr('data-seqNo'));
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var medicineName = $(this).parent().children('div').eq(1).children('span').html();
        var params = {
            "oprInfo":{
                "opCode": "1254",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生删除治疗计划中药品【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "ptCourseId": $bb.getPageParams().ptCourseId,
            "medicineId": medicineId,
            "seqNo": seqNo,
        };
        $bb.toastConfirmShow(confirmDeleteMed, params, "确认是否删除？")
    }

    /**
     * 移动药物
     */
    var onMoveMed = function(){
    	var obj = $bb.getPageParams();
        var moveDirection = $(this).data("moveDirection");
        var medicineName = $(this).parent().find('.course-list-medicineName span').html();
        var seqNo = parseInt($(this).parent("th").attr('data-seqNo'));
        var medicineId = $(this).parent("th").attr('data-medicineId');
        var params = {
            "oprInfo":{
                "opCode": "1252",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生移动药物【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "ptCourseId":obj.ptCourseId,
            "seqNo": seqNo,
            "moveDirection": moveDirection,
            "medicineId": medicineId
        };
        $servers.ajaxMoveMedicine(params,tableInit);
    }

    /**
     * 添加天数
     */
    var increaseDay = function() {
    	var obj = $bb.getPageParams();
        var seqDay = $('#'+ domId +' tbody tr:first-child td').html() == '暂无数据' ? 1 : $('#'+ domId +' tbody tr').length;
        var params = {
            "oprInfo":{
                "opCode": "1250",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生给【" + obj.courseName + "】疗程添加第【" + seqDay + "】天",
                "channelType": "2",
                "channelId": channelId
            },
            "ptCourseId":obj.ptCourseId,
            "seqDay":seqDay
        };
        $servers.ajaxIncreaseDay(params,tableInit);
    }

    /**
     * 请求删除接口
     */
    var confirmReduceDay = function(params) {
        $servers.ajaxReduceDay(params,tableInit);
    }

    /**
     * 删除天数
     */
    var reduceDay = function() {
    	var obj = $bb.getPageParams();
        var seqDay = parseInt($(this).parents("tr").attr('data-index'));
        var params = {
            "oprInfo":{
                "opCode": "1255",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生删除疗程【" + obj.courseName + "】中的【" + seqDay + "】天",
                "channelType": "2",
                "channelId": channelId
            },
            "ptCourseId":obj.ptCourseId,
            "seqDay":seqDay,
        };
        $bb.toastConfirmShow(confirmReduceDay,params,"是否确认删除第" + seqDay + "天的用药数据");
    }

    /**
     * 单元格设置value
     */
    var onSetValueCell = function(){
        var value = parseFloat( $(this).val() );
        var datas = $(this).data("datas");
        if( value == datas.oldValue ){
        	$(this).parent(".medicine-dose").html(datas.oldValue);
        }else if( value < 0 ) {
            $bb.toastShow('请输入大于0的数字');
        }else{
            var obj = $bb.getPageParams();
            var params = {
                "oprInfo":{
                    "opCode": "1253",
                    "opType": "2",
                    "opNote": "【" + doctorName + "】医生给【" + obj.courseName + "】疗程调整第【" + datas.seqDay + "】天药品【" + datas.currMedicine.medicineName + "】的剂量",
                    "channelType": "2",
                    "channelId": channelId
                },
                "ptCourseId":obj.ptCourseId,
                "medicineId":datas.currMedicine.medicineId,
                "seqDay":datas.seqDay,
                "medicineDose":value,
            };
            $servers.ajaxChangeMedicineDose(params,tableInit);
        }
    }

    /**
     * 给疗程库中的疗程调整某天某种药品的剂量
     */
    var onChangeMedicineDose = function(){
        if( $(this).children('input').length ) return false;
        var medicines = $(this).data("medicines");
        var seqDay = parseInt( $(this).parent("tr").attr("data-index") );
        var medicineId = $(this).attr("data-medicineId");
        var currMedicine = $servers.getCurrMedicine(medicines,medicineId);
        var oldValue = $(this).html();
        var initValue = ( oldValue == 0 || !oldValue ) ? currMedicine.medicineDose : oldValue;
        $(this).html('<input class="text-center" type="number" min="0">');
        var $input = $(this).children();
        $input.focus().val(initValue).unbind("blur");
        $input.data("datas",{"currMedicine":currMedicine,"seqDay":seqDay,"oldValue":oldValue});
        $input.blur(onSetValueCell);
    }

    /**
     * 药品剂量查询成功后的回调函数
     */
    var ajaxListPtCourseMedDoseCallBack = function(data,datas){
        if( data.rows.length > 0 ){
            // 疗程已有治疗开始时间，则编辑疗程进去之后，不能进行任何操作
            var flag = data.rows[0].dealDate ? false : true;
        	$ui.table({
                "id": domId,
                "medicines": datas.medicines,
                "days":$servers.handleDays(data.rows,datas.medicines),
                "flag":flag
            });
            if( flag ){
                // 新增药物
                $('#'+ domId +' thead tr th.add-medicine').unbind('click');
                $('#'+ domId +' thead tr th.add-medicine').click(onAddClick);
                // 删除药物
                $('.delBtn').unbind('click');
                $('.delBtn').click(deleteMed);
                // 移动药物
                $(".course-list-upBtn").unbind("click");
                $(".course-list-upBtn").data("moveDirection","up");
                $(".course-list-upBtn").click(onMoveMed);
                $(".course-list-downBtn").unbind("click");
                $(".course-list-downBtn").data("moveDirection","down");
                $(".course-list-downBtn").click(onMoveMed);
                // 点击添加天数的按钮
                $('#increaseDay').unbind('click');
                $('#increaseDay').click(increaseDay);
                // 删除疗程中的某一天
                $('.delDay').unbind('click');
                $('.delDay').click(reduceDay);
                // 添加、修改用药剂量
                $(".medicine-dose").unbind("click");
                $(".medicine-dose").data("medicines",datas.medicines);
                $(".medicine-dose").bind("click",onChangeMedicineDose);
            }
        }
    }

    /**
     * 查询药品信息成功后的回调函数
     */
    var ajaxMedicineInfoCallBack = function(data,datas){
    	datas.medicines = data.courseMedicine.rows;
    	var decodeDrugDoses = $bb.code.getDeCodeByName("drugDoses");
    	var params = {
			"oprInfo":{
				"channelType":"2",
				"channelId":channelId,
			},
			"busiId":datas.ptCourseId,
			"userId":datas.info.userId,
			"deList":[
				{
					"deCode":decodeDrugDoses
				}
			]
		};
		$servers.ajaxListPtCourseMedDose(params,ajaxListPtCourseMedDoseCallBack,datas);
    }

    /**
     * table初始化
     */
    var tableInit = function(){
    	var params = $bb.getPageParams();
    	$servers.ajaxMedicineInfo(params,ajaxMedicineInfoCallBack);
    }
    

    treatPlanCourseEdit.init = function(){
    	var params = $bb.getPageParams();
    	// 基本信息
        $ui.info({
            "id":"treatPlanCourseEditInfo",
            "info":params.info
        });
        $ui.title({
			"id":"treatPlanCourseEditTitle",
			"stageName":params.stageName,
			"courseName":params.courseName
		});
		tableInit();
    }

   return treatPlanCourseEdit;
});
